package com.xinqi.util.sqlsession;

import com.baomidou.mybatisplus.core.mapper.Mapper;
import com.xinqi.mapper.BlogMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author xin麒
 * @date 2023/8/24 23:06
 */
public class SingleSqlSession {
    private volatile SqlSession sqlSession;
    private AtomicBoolean lock = new AtomicBoolean(true);
    //true表示该连接已经被一个线程占用了，其他线程不可以使用该连接，除非锁被释放，其他线程便可以获取锁，同时也只有获取到锁的才可以使用该sqlsession连接


    public SqlSession getSqlSession() {
        return getSqlSession(false);
    }
    public SqlSession getSqlSession(boolean isAutoCommit) {
        if (this.sqlSession == null) {
            synchronized (this) {
                if (this.sqlSession == null) {
                    try {
                        //获取核心配置文件的输入流
                        InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
                        //获取SqlSessionFactoryBuilder对象
                        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
                        //获取SqlSessionFactory对象
                        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
                        //获取sql的会话对象SqlSession(会自动提交事务)，是MyBatis提供的操作数据库对象
                        this.sqlSession = sqlSessionFactory.openSession(isAutoCommit);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return this.sqlSession;
    }

    public void commit() {
        sqlSession.commit();
        unlock();
    }

    public void unlock(){
        lock.getAndSet(true);
    }
    public boolean lock() {
        return lock.compareAndSet(true,false);
    }
}
